<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-dialog/paper-dialog.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../bower_components/paper-input/paper-input-error.html">
<link rel="import" href="../../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../bower_components/mist-list/mist-list-actions-behavior.html">
<link rel="import" href="../../bower_components/mist-list/mist-list-actions.html">


<dom-module id="other-cloud-machine-actions">
  <template>
    <style include="shared-styles">
      :host {
        display: inline;
        color: rgba(255,255,255,0.87);
      }
    </style>
    <dialog-element id="other-confirm"></dialog-element>
    <iron-ajax id="request"
            handle-as="json"
            loading="{{loadingData}}"
            on-response="handleResponse"
            on-error="handleError"></iron-ajax>
    <slot>
        <mist-list-actions actions=[[actions]]></mist-list-actions>
    </slot>
  </template>
  <script>
    OTHER_CLOUD_MACHINE_ACTIONS = {
      'remove': {
        'name': 'remove',
        'icon': 'remove',
        'confirm': true,
        'multi': true
      }
    };

    Polymer({
      is: 'other-cloud-machine-actions',

      behaviors: [MistListActionsBehavior],

      properties: {
        items: { 
          type: Array,
          value: function () { return [] },
        },
        actions: { 
          type: Array,
          value: function () { return [] },
          notify: true
        },
        type: {
          type: String,
          value: 'host'
        }
      },

      listeners: {
        'confirmation': 'confirmAction',
        'select-action': 'selectAction',
      },

      attached: function() {
        this.$.request.headers["Content-Type"] = 'application/json';
        this.$.request.headers["Csrf-Token"] = CSRF_TOKEN;
        this.$.request.method = "POST";
      },

      computeItemActions: function(machine) {
        // single record actions
        var arr = [];
        if (machine) {
          arr.push('remove');
        }
        return arr;
      },

      computeActionListDetails: function (actions) {
        var ret = [];
        for (var i=0; i<actions.length; i++) {
            ret.push(OTHER_CLOUD_MACHINE_ACTIONS[actions[i]]);
        }
        return ret;
      },

      _remove: function() {
        //set up iron ajax
        this.$.request.headers["Content-Type"] = 'application/json';
        this.$.request.headers["Csrf-Token"] = CSRF_TOKEN;
        this.$.request.method = "POST";
        payload = {'action': 'remove'};
        this.$.request.body = payload;

        for (var i = 0; i < this.items.length; i++) {
          this.$.request.url = "/api/v1/machines/"+this.items[i].id
          this.$.request.generateRequest();
          this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail:  {msg: 'Removing ' + this.items[i].name , duration: 1000} }));
        }
      },

      _showDialog: function(info) {
          var dialog = this.shadowRoot.querySelector('dialog-element#other-confirm');
          if (info) {
            for (var i in info) {
                dialog[i] = info[i];
            }
          }
          dialog._openDialog();
      },

      confirmAction: function(e){
        if (e.detail.confirmed)
          this.performAction(this.action, this.items);
      },

      selectAction: function(e){
        if (this.items.length) {
          var action = e.detail.action;
          this.set('action', action);
          // console.log('perform action mist-action', this.items);
          if (action.confirm && action.name != 'tag') {
            var property = ['machine'].indexOf(this.type) == -1 ? "name" : "domain",
                plural = this.items.length == 1 ? '' : 's',
                count = this.items.length > 1 ? this.items.length+' ' : '';
            //this.tense(this.action.name) + " " + this.type + "s can not be undone. 
            this._showDialog({
                title: this.action.name + ' ' + count + this.type + plural+'?',
                body: "You are about to " + this.action.name + " " + this.items.length + " " + this.type + plural+".",
                list: this._makeList(this.items, property),
                action: action.name,
                danger: true,
                reason: this.type + "." + this.action.name
            });
          } else {
            this.performAction(this.action, this.items);
          }
        }
      },

      performAction: function(action, items) {
        // console.log('perform action ',action)
        if (action && action.name == 'remove') {
          this._remove();
        }
      },

      handleResponse: function(e) {
        if (this.$.request && this.$.request.body && this.$.request.body.action)
          this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail:  {msg: 'Action: '+this.$.request.body.action+' successfull', duration: 3000} }));
      },

      handleError: function(e) {
        // console.log(e.detail.request.xhr.statusText);
        this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: {msg: 'Error: ' + e.detail.request.xhr.status +" "+ e.detail.request.xhr.statusText, duration: 5000} }));

      },

      _makeList: function(items, property){
        if (items && items.length)
          return items.map(function(item){
            return item[property];
          });
      }
    });
  </script>
</dom-module>